<template>
	<view class="content">
		<input type="text" v-model="username" placeholder="用户名" />
		<input type="password" v-model="password" placeholder="密码" />
		<button type="default" :loading="loading" @click="userLogin">登录</button>
		<view class="link">
			<navigator url="/pages/reg/reg">
				<text>没有账号，去注册</text>
			</navigator>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				username: '',
				password: '',
				loading: false
			}
		},
		onLoad() {
			if (uni.getStorageSync('uni_id_token_expired') > Date.now() && uni.getStorageSync('uni_id_token')) {
				uni.redirectTo({
					url: '/pages/list/list'
				})
			}
		},
		methods: {
			...mapMutations(['login']),
			userLogin() {
				if (this.loading) {
					return
				}
				if (!this.username) {
					uni.showModal({
						content: '用户名不可为空',
						showCancel: false
					})
					return
				}
				if (!this.password) {
					uni.showModal({
						content: '密码不可为空',
						showCancel: false
					})
					return
				}
				this.loading = true
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'login',
						params: {
							username: this.username,
							password: this.password,
							needPermission: true
						}
					}
				}).then((res) => {
					if (res.result.code === 0) {
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						})
						this.login({
							username: res.result.username,
							role: res.result.role || null,
							token: res.result.token,
							tokenExpired: res.result.tokenExpired
						})
						uni.reLaunch({
							url: '/pages/mine/mine'
						})
					} else {
						uni.showModal({
							content: res.result.msg,
							showCancel: false
						})
					}
				}).catch((err) => {
					console.log(err)
					uni.showModal({
						content: err.errMsg || '请求服务器出错，请稍后再试',
						showCancel: false
					})
				}).finally(() => {
					this.loading = false
				})
			}
		}
	}
</script>

<style>

</style>
